package com.feilo.job;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.feilo.service.DevinfoService;
import com.feilo.service.DistanceService;
import com.feilo.util.PropertiesUtil;



/**
 * quartz 工作类
 * @author zhangrl
 *
 */
public class DistanceJob implements Job {

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		System.out.println("DistanceJob is working...");
		String ak = PropertiesUtil.getDBString("ak");
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");//格式化对象
		Calendar calendar = Calendar.getInstance();//日历对象
		calendar.setTime(date);//设置当前日期
		calendar.add(Calendar.DAY_OF_MONTH, -1);//天数-1
		String format = sdf.format(calendar.getTime());
		System.out.println("begin_time:"+format);
		long begin_time = 0 ;
		try {
			begin_time = sdf.parse(format).getTime()/1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long end_time = System.currentTimeMillis()/1000;
		//获取所有设备号（imei）
		String[] imeis = DevinfoService.getImeisFromDevinfo();
		for(String imei : imeis){
			//获取1天的历史轨迹点数据,然后以每100条轨迹数据组成1个轨迹点url的参数（由于太多的轨迹点组成的url会超长，因此出此下策）
			String[] waypoint = DistanceService.getWayPoint(imei,begin_time, end_time);
			//根据轨迹点和ak参数组成符合百度计算距离的url数组
			String[] urls = DistanceService.getDistanceURLs(waypoint,ak);
			//根据每个url的返回结果计算实际距离，并返回计算结果数组
			float[] distances = DistanceService.getDistanceData(urls);
			//计算出一天的总长后存入数据库
			float total = 0 ;
			for(float d : distances){
				total += d ;
			}
			insertDistance(imei, date, total);
			System.out.println("imei="+imei+",date="+date+",total="+total);
		}
	}

	
	/**
	 * 把设备号、日期、所经过距离等数据存入数据库
	 * @param imei     设备号
	 * @param date     日期
	 * @param distance 距离
	 */
	private void insertDistance(String imei, Date date, float total) {
		DistanceService.insertDistance(imei, date, total);		
	}


}
